package middleware

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
)

// CorsMw 跨域中间件
func CorsMw(_ log.Logger) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if tr, ok := transport.FromServerContext(ctx); ok {
				tr.ReplyHeader().Set("Access-Control-Allow-Origin", "*")                                  // 允许请求的地址
				tr.ReplyHeader().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,PATCH,DELETE") //允许请求的方法
				//tr.ReplyHeader().Set("Access-Control-Allow-Credentials", "true")// 证书
				//tr.ReplyHeader().Set("Access-Control-Allow-Headers", "Content-Type,User-Agent,Content-Length,Authorization")

				// Do something on entering
				//tr.Endpoint()
				//spew.Dump(tr.RequestHeader())

			}
			return handler(ctx, req)
		}
	}
}
